'''
Created on 15.02.2011

@author: public
'''

import sync
import threading
import time
import logging
import const
import auth
import util

CONSOLE_SEPARATOR_LINE = '****************************************************************'

__logger = None

def main() :
    
    logging.config.fileConfig('../' + const.LOGGING_CFG_FILE)
    global __logger    
    __logger = logging.getLogger('runner')
    
    syncPeriod = int (util.readConfigProperty('params', 'period'))
            
    #currTime = time.strftime(const.DATE_TIME_FMT, time.localtime())
    periodRepresentation = time.strftime("%H:%M:%S", time.gmtime(syncPeriod))
    
    print '\n\n\n\n'
    
    __logger.info(CONSOLE_SEPARATOR_LINE)
    __logger.info('Starting periodic task every [%s]' % (periodRepresentation, ))
    __logger.info(CONSOLE_SEPARATOR_LINE)
            
    timerEvent = threading.Event() 
    timerThread = threading.Thread(target=__repeat, args=(timerEvent, syncPeriod, sync.runSync))
     
    timerThread.start()

def __repeat(event, every, action):
    ''' Scheduled running [action] every [every] seconds in separate thread.
    event.isSet() used to stop process. 
    '''
    
    authUrl = util.readConfigProperty('auth', 'url')
    user = util.readConfigProperty('auth', 'user')
    psw = util.readConfigProperty('auth', 'psw')
    opener = auth.authorize(authUrl, user, psw)
        
    while True:        
        #start = time.time()
        __logger.info('job >')
          
        if event.isSet(): 
            break
    
        loToken = util.readConfigProperty('auth', 'logged_out_token')    
        auth.checkOpener(opener, authUrl, loToken)
        while (opener.needsReauth):
            opener = auth.authorize(authUrl, user, psw)        
         
        t = threading.Thread(target=action, args=(opener,))
        t.start()
                         
        event.wait(every)
         

if __name__ == '__main__':    
    main()
 
#time.sleep(10)
#ev.set()
  
#t1.join() 

#print "quit" 